package com.chinackts.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Lianhong
 * @since 2022/3/16
 */
public class RequestUtil {

    public static HttpServletRequest request() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return null;
        return attributes.getRequest();
    }

    public static String getRequestId() {
        HttpServletRequest request = request();
        if (request == null) return null;
        String requestURI = request.getRequestURI();
        return getId(requestURI, "/e-port/(.*?)/");
    }

    public static String getRequestId(HttpServletRequest request) {
        if (request == null) return null;
        String requestURI = request.getRequestURI();
        return getId(requestURI, "/e-port/(.*?)/");
    }

    private static String getId(String value, String regx) {
        Pattern pattern = Pattern.compile(regx);// 匹配的模式
        Matcher m = pattern.matcher(value);
        while (m.find()) {
            return m.group(1);
        }
        return StringUtils.EMPTY;
    }
}
